import java.util.ArrayList;
import java.util.Arrays;

public class MyArrrayList {
    private int[] arrayList;
    private int usedSize;
    public static final int DEFAULT_CAPACITY = 10;
    public MyArrrayList() {
        this.arrayList = new int[DEFAULT_CAPACITY];
    }
    public MyArrrayList(int initialCapacity) {
        this.arrayList = new int[initialCapacity];
    }
    //增加一个新数据 但需要检查容量是否已满
    public void add(int data){
        if(isFull()){
            //如果满了需要进行扩容
            this.arrayList = Arrays.copyOf(arrayList, arrayList.length*2);
        }
        this.arrayList[this.usedSize] = data;
        this.usedSize++;
    }
    public boolean isFull(){
        if(this.usedSize == this.arrayList.length){
            return true;
        }
        return false;
    }
    //添加指定位置的数据 数据结构比较严谨 所以在当前逻辑下 凡是要添加数据都要检查容量是否已经满了
    public void add(int pos ,int data){
        checkPos(pos);
        if(isFull()){
            this.arrayList = Arrays.copyOf(arrayList, arrayList.length*2);
        }
        //将指定位置之后的数组往后移
        for(int i = this.usedSize-1; i >= pos; i--){
            this.arrayList[i + 1] = this.arrayList[i];
        }
        this.arrayList[pos] = data;
        usedSize++;
    }
//该方法逻辑比较简单 对于要查找的数要么有要么没有
    public boolean contains(int toFind){
        for(int i = 0;i < this.usedSize;i++){
            if(this.arrayList[i] == toFind){
                return true;
            }
        }
        return false;
    }

    public int indexOf(int toFind){
        for(int i = 0;i < this.usedSize;i++){
            if(this.arrayList[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    public int get(int pos){
        //这个方法逻辑就要谨慎一点 需要对pos的范围进行判定
        checkPos(pos);
        return this.arrayList[pos];
    }
//替换数据
    public void set(int pos,int value){
        checkPos(pos);
        this.arrayList[pos] = value;
    }
//删除数据
    public void remove(int toRemove){
        int index = this.indexOf(toRemove);
        if(index == -1){
            System.out.println("没有这个数据");
            return;
        }
        for(int i = index;i < this.usedSize - 1;i++){
            this.arrayList[i] = this.arrayList[i+1];
        }
        usedSize--;
    }

    public int size(){
        return this.usedSize;
    }

    public void clear(){
        //若是引用类型 需要将每个元素置空为null
        /*
           for(int i = 0;i < usedSize; i++){
               this.arrayList[i] = null;
           }
        */
        this.usedSize = 0;
    }

    public void display(){
        for(int i = 0; i < this.usedSize; i++){
            System.out.print(this.arrayList[i]+" ");
        }
    }
    public void checkPos(int pos){
        if(pos < 0 || pos >= this.usedSize){
            throw new PosOutOfBoundsException(pos + "位置不合法");
        }
    }
}
